﻿using DTcms.Core.IServices;
using DTcms.Core.IServices.Alipay;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DTcms.Core.API.Controllers
{
    [Area("api")]
    [Route("api/alipay/notify")]
    [ApiController]
    public class AlipayNotifyController : ControllerBase
    {
        private readonly IAlipayNotify _alipayNotify;
        private readonly IMemberRechargeService _memberRechargeService;
        public AlipayNotifyController(IAlipayNotify alipayNotify, IMemberRechargeService memberRechargeService)
        {
            _alipayNotify = alipayNotify;
            _memberRechargeService = memberRechargeService;
        }

        /// <summary>
        /// 支付成功回调
        /// 示例：/api/alipay/notify/transactions/pc
        /// </summary>
        [HttpPost("transactions/{type}")]
        public async Task<IActionResult> Transactions([FromRoute] string type)
        {
            bool result = false;
            if (type.ToLower() == "pc")
            {
                var model = await _alipayNotify.PagePay(Request);
                //判断充值订单还是商品订单
                if (model.OutTradeNo.StartsWith("RN"))
                {
                    //修改充值订单状态
                    result = await _memberRechargeService.CompleteAsync(model.OutTradeNo);
                }
            }
            //返回结果
            if (!result)
            {
                return BadRequest("fail");
            }
            return Ok("success");
        }

    }
}
